﻿using MaterialManagement.API.Application.Command.ERP;
using MaterialManagement.API.Dtos;
using MaterialManagement.Domain.ERP;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Interface;
using MediatR;
using Process.Domain;

namespace MaterialManagement.API.Application.Handler.ERP
{
    public class GetProcessInspectionHandler : IRequestHandler<GetProcessInspectionCommand, APIResult<List<ProcessInspectionDto>>>
    {
        private readonly IBaseRepository<ProcessInspectionModel> processRepo;
        private readonly IBaseRepository<ProductionOrders> productRepo;

        public GetProcessInspectionHandler(IBaseRepository<ProcessInspectionModel> processRepo,
                                           IBaseRepository<ProductionOrders> productRepo)
        {
            this.processRepo = processRepo;
            this.productRepo = productRepo;
        }
        public Task<APIResult<List<ProcessInspectionDto>>> Handle(GetProcessInspectionCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ProcessInspectionDto>> result = new APIResult<List<ProcessInspectionDto>>();
            var res = processRepo.GetAll().Where(x => x.IsDel == false);
            if (!string.IsNullOrEmpty(request.InspectionOrderCode))
            {
                res = res.Where(x=>x.InspectionOrderCode.Contains(request.InspectionOrderCode));
            }
            var product = productRepo.GetAll().Where(x=>x.IsDel == false);
            var query = from x in res
                        join y in product on x.ProductionOrderCode equals y.ProductionOrdersCode
                        select new ProcessInspectionDto
                        {
                            ProductionOrderCode = x.ProductionOrderCode,
                            State = x.State,
                            DispatchId = x.DispatchId,
                            InspectionDate = x.InspectionDate,
                            InspectionOrderCode = x.InspectionOrderCode,
                            InspectionOrderId = x.InspectionOrderId,
                            InspectionOrderName = x.InspectionOrderName,
                            InspectionQuantity = x.InspectionQuantity,
                            Inspector = x.Inspector,
                            IsDel = x.IsDel,
                            ProductCode = y.ProductCode,
                            ProductName = y.ProductName,
                            ProductType = y.ProductType,
                            QualifiedQuantity = x.QualifiedQuantity,
                            Unit = y.Unit,
                            UnqualifiedQuantity = x.UnqualifiedQuantity,
                            SpecificationModel = y.SpecificationModel
                        };
            result.Message = "显示成功";
            result.Data = query.ToList();
            result.Code = APIEnum.Ok;
            return Task.FromResult(result);
        }
    }
}
